from django.conf import settings
from django.urls import resolve
from django.http import HttpResponseForbidden


class LoginRequiredForMediaMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 检查请求是否指向MEDIA_URL，并且用户未登录或不在 reviewer 组中
        if request.path.startswith(settings.MEDIA_URL):
            if not request.user.is_authenticated or (
                    not request.user.groups.filter(name='reviewer').exists() and not request.user.is_superuser):
                return HttpResponseForbidden('You must be a logged-in reviewer or superuser to access this resource.')
        response = self.get_response(request)
        # 添加Cache-Control和Pragma头部来禁止浏览器缓存
        if request.path.startswith(settings.MEDIA_URL):
            response['Cache-Control'] = 'no-cache, must-revalidate'
            response['Pragma'] = 'no-cache'
        return response
